// miniprogram/pages/blog/blog.js
let keyword = ''
Page({
  /**
   * 页面的初始数据
   */
  data: {
    modalShow: false,   // 控制地步碳层是否显示
    blogList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._loadBlogList()
  },
  _loadBlogList (start = 0, type = 'load') {
    wx.showLoading({
      title: '加载中...'
    })
    wx.showNavigationBarLoading()
    wx.cloud.callFunction({
      name: 'blog',
      data: {
        start,
        keyword,
        count: 10,
        $url: 'list'
      }
    }).then(res => {
      if (type == 'refresh') {
        this.setData({
          blogList: res.result
        })
      } else {
        this.setData({
          blogList: this.data.blogList.concat(res.result)
        })
      }

      wx.hideLoading()
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },
  // 发布功能
  onPublish () {
    // 判断用户是否授权
    wx.requestSubscribeMessage({
      tmplIds: ['JkrMpvhIrmfRU3BdLeWlzuGka-9BMJn-_6v52-94vY4'],
      success: (res) => {
        wx.getSetting({
          success: (res) => {
            if (res.authSetting['scope.userInfo']) {
              wx.getUserInfo({
                withCredentials: 'false',
                lang: 'zh_CN',
                timeout: 10000,
                success: (result) => {
                  this.onLoginSuccess({
                    detail: result.userInfo
                  })
                },
                fail: () => { },
                complete: () => { }
              });
            } else {
              this.setData({
                modalShow: true
              })
            }
          }
        })
      }
    })
  },
  onLoginSuccess (event) {
    const detail = event.detail
    wx.navigateTo({
      url: `../blog-edit/blog-edit?nickName=${detail.nickName}&avatarUrl=${detail.avatarUrl}`
    })

  },
  onLoginFail () {
    wx.showModal({
      title: '授权之后才能发布',
      content: ''
    })
  },
  goComment (event) {
    wx.navigateTo({
      url: '../../pages/blog-comment/blog-comment?blogid=' + event.target.dataset.blogid
    })
  },

  onSearch (event) {
    this.setData({ blogList: [] })
    keyword = event.detail.keyword
    this._loadBlogList(0)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // this.setData({
    //   blogList: []
    // })
    this._loadBlogList(0, 'refresh')
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this._loadBlogList(this.data.blogList.length)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (event) {
    const blogObj = event.target.dataset.blog
    return {
      title: blogObj.content,
      path: `/pages/blog-comment/blog-comment?blogid=${blogObj._id}`
    }
  }
})